package com.platform.qujia.utils.tonglianpay;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/***
 * 通联支付工具类
 */
@Slf4j
public class TLPayUtil {

    //生产环境
    private static final String SYB_APIURL = "https://vsp.allinpay.com/apiweb/unitorder";

    public static HashMap tLTradePay(TLPayParam tlPayParam) throws Exception {
        HashMap resultInfo = new HashMap();
        HttpConnectionUtil http = new HttpConnectionUtil(SYB_APIURL+"/pay");
        http.init();
        TreeMap<String,String> params = new TreeMap<String,String>();
        if(!SybUtil.isEmpty(tlPayParam.getSysOrgId()))
            params.put("orgid", tlPayParam.getSysOrgId());
        params.put("cusid", tlPayParam.getCusId());
        params.put("appid", tlPayParam.getSybAppId());
        params.put("version", "11");
        params.put("trxamt", String.valueOf(tlPayParam.getTrxAmt()));
        params.put("reqsn", tlPayParam.getReqSn());
        params.put("paytype", tlPayParam.getPayType());
        params.put("randomstr", SybUtil.getValidatecode(8));
        params.put("body", tlPayParam.getBody());
        params.put("remark", tlPayParam.getRemark());
//		params.put("validtime", validtime);
        params.put("acct", tlPayParam.getAcct());
        params.put("notify_url", tlPayParam.getNotifyUrl());
//		params.put("limit_pay", limit_pay);
        params.put("sub_appid", tlPayParam.getSubAppId());
//		params.put("goods_tag", goods_tag);
//		params.put("benefitdetail", benefitdetail);
//		params.put("chnlstoreid", chnlstoreid);
//		params.put("subbranch", subbranch);
//		params.put("extendparams", extendparams);
//		params.put("cusip", cusip);
//		params.put("fqnum", fqnum);
//		params.put("idno", idno);
//		params.put("truename", truename);
//		params.put("asinfo", asinfo);
        params.put("signtype", tlPayParam.getSIGN_TYPE());
        String appkey = "";
        switch (tlPayParam.getSIGN_TYPE()){
            case "RSA":
                appkey = tlPayParam.getSYB_RSACUSPRIKEY();
                break;
            case "SM2":
                appkey = tlPayParam.getSYB_SM2PPRIVATEKEY();
                break;
            case "MD5":
                appkey = tlPayParam.getSYB_MD5_APPKEY();
                break;
        }
        params.put("sign", SybUtil.unionSign(params, appkey, tlPayParam.getSIGN_TYPE()));
        //System.out.println("params:" + params);
        byte[] bys = http.postParams(params, true);
        String result = new String(bys,"UTF-8");
        Map<String,String> map = handleResult(result, tlPayParam);
//      返回格式：
//        {randomstr=192385841078, cusid=553588055418RR8, appid=00226421,
//        sign=SbLmQ9bqr766wliej9zIvKPu5LmlUuLvVVYHC5sYEON8G+PZ0SKqvga5P12Q+Vsgi59V12yi7fxWcrFXCPlnxwYc+gAyl2Mxa79IUrJmNXgjT0Ri7dM3qynRqLfoCKQhEtwlgzH5uwzd8pk800yqjT6qZ2d3T3knvbXEwVty5yU=,
//        payinfo={
//                "appId": "wx60eecce847c74bcc",
//                "timeStamp": "1639540550",
//                "nonceStr": "557bc5d20695475a99dc935d4a2e023d",
//                "package": "prepay_id=wx15115550909410aa600ce7d5f0a1360000",
//                "signType": "RSA",
//                "paySign": "242DbibuSpyK/YVQflzwNaR6Pg9h2ZkwmNU+JmRzsHC/8D5l2KLcJqg8Ik8Ia6zX7OFg1zUHyn2eHeH8HmC3AvkOnZ1vHTG1CXANF3oSqcvarmmbRh6on9aFzB85cveE1D1lNIF1LJ9Kiy6A+Bijk7GXkYl/b8ZfMZwlpj3F4YRrrZWkroOMDsJepU/CHIJwe3d3j6PbJBIOVSAwvxoLsnaL2lQ2DFWKpDrUQlnWuQPL8wB17oe6QslbC+3hO4T6VYtl/qlgr4NGLrHHgqR4I3aU/sjCB8fzxtP2/jipZsjOx8ILvuxXGxvifil+YIm6KnzvaO8Yetk7JzAM0pM//Q=="
//             }, trxid=211215113309477077, trxstatus=0000, reqsn=1639540552221, retcode=SUCCESS
//        }
        log.info("通联拉起支付返回字段：" +map);
        if("0000".equals(map.get("trxstatus"))){
            if ("W06".equals(tlPayParam.getPayType())){
                Map payInfoMap = JSON.parseObject(map.get("payinfo"), Map.class);
                resultInfo.put("payTimeStamp", payInfoMap.get("timeStamp"));
                resultInfo.put("paynonceStr", payInfoMap.get("nonceStr"));
                resultInfo.put("paySignType", payInfoMap.get("signType"));
                resultInfo.put("payPackage", payInfoMap.get("package"));
                resultInfo.put("paySign", payInfoMap.get("paySign"));
                resultInfo.put("payAppId", payInfoMap.get("appId"));
                resultInfo.put("signType", payInfoMap.get("signType"));
            }else {
                resultInfo.put("source", map.get("payinfo"));           //支付宝流水号或支付宝支付链接
            }
            resultInfo.put("merchantsNumber", map.get("trxid")); //商户单号（商户）
            resultInfo.put("ordNo", map.get("reqsn"));
            //resultInfo.put("bizMsg", respData.get("bizMsg"));
            //resultInfo.put("bizCode", respData.get("bizCode"));
            //resultInfo.put("sxfUuid", respData.get("sxfUuid"));
            //resultInfo.put("uuid", respData.get("uuid"));
            //resultInfo.put("orgId", result.get("orgId"));
            //resultInfo.put("reqId", result.get("reqId"));
        }else {
            resultInfo.put("code", map.get("trxstatus"));
            resultInfo.put("msg", map.get("errmsg"));
        }
        return resultInfo;
    }

    public static HashMap tLClassSettle(TLPayParam tlPayParam) throws Exception {
        HashMap resultInfo = new HashMap();
        HttpConnectionUtil http = new HttpConnectionUtil("https://tlgd-test.allinpaygd.com/ug/gateway.do");
        http.init();
        TreeMap<String,String> params = new TreeMap<String,String>();
        params.put("appId", "test");
        params.put("charset", "utf-8");

        params.put("signtype","MD5");
        params.put("version", "1.0");
        params.put("timestamp", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        params.put("service", "oil.advance.settle");

        params.put("bizContent", "{\"oilStationNo\":\"S0015\",\"shiftsMask\":\"3\",\"shiftsTime\":\"20220114\",\"sysId\":\"1910291133258885426\"}");
        params.put("sign", SybUtil.unionSign(params, "123456", "MD5"));



       //params.put("sysId", "1910291133258885426");
       // params.put("cusid", tlPayParam.getCusId());


        //params.put("appKey", "123456");
//        params.put("oilStationNo", "S0015");
//        params.put("班次号", "S0015002");


//        params.put("paytype", tlPayParam.getPayType());
//        params.put("randomstr", SybUtil.getValidatecode(8));
//        params.put("body", tlPayParam.getBody());
//        params.put("remark", tlPayParam.getRemark());
////		params.put("validtime", validtime);
//        params.put("acct", tlPayParam.getAcct());
//        params.put("notify_url", tlPayParam.getNotifyUrl());
////		params.put("limit_pay", limit_pay);
//        params.put("sub_appid", tlPayParam.getSubAppId());
//		params.put("goods_tag", goods_tag);
//		params.put("benefitdetail", benefitdetail);
//		params.put("chnlstoreid", chnlstoreid);
//		params.put("subbranch", subbranch);
//		params.put("extendparams", extendparams);
//		params.put("cusip", cusip);
//		params.put("fqnum", fqnum);
//		params.put("idno", idno);
//		params.put("truename", truename);



       // String appkey = "";
//        switch (tlPayParam.getSIGN_TYPE()){
//            case "RSA":
//                appkey = tlPayParam.getSYB_RSACUSPRIKEY();
//                break;
//            case "SM2":
//                appkey = tlPayParam.getSYB_SM2PPRIVATEKEY();
//                break;
//            case "MD5":
//                appkey = tlPayParam.getSYB_MD5_APPKEY();
//                break;
//        }

        //System.out.println("params:" + params);
        byte[] bys = http.postParams(params, true);
        String result = new String(bys,"UTF-8");

        Map<String,String> map = handleResult(result, new TLPayParam());
//      返回格式：
//        {randomstr=192385841078, cusid=553588055418RR8, appid=00226421,
//        sign=SbLmQ9bqr766wliej9zIvKPu5LmlUuLvVVYHC5sYEON8G+PZ0SKqvga5P12Q+Vsgi59V12yi7fxWcrFXCPlnxwYc+gAyl2Mxa79IUrJmNXgjT0Ri7dM3qynRqLfoCKQhEtwlgzH5uwzd8pk800yqjT6qZ2d3T3knvbXEwVty5yU=,
//        payinfo={
//                "appId": "wx60eecce847c74bcc",
//                "timeStamp": "1639540550",
//                "nonceStr": "557bc5d20695475a99dc935d4a2e023d",
//                "package": "prepay_id=wx15115550909410aa600ce7d5f0a1360000",
//                "signType": "RSA",
//                "paySign": "242DbibuSpyK/YVQflzwNaR6Pg9h2ZkwmNU+JmRzsHC/8D5l2KLcJqg8Ik8Ia6zX7OFg1zUHyn2eHeH8HmC3AvkOnZ1vHTG1CXANF3oSqcvarmmbRh6on9aFzB85cveE1D1lNIF1LJ9Kiy6A+Bijk7GXkYl/b8ZfMZwlpj3F4YRrrZWkroOMDsJepU/CHIJwe3d3j6PbJBIOVSAwvxoLsnaL2lQ2DFWKpDrUQlnWuQPL8wB17oe6QslbC+3hO4T6VYtl/qlgr4NGLrHHgqR4I3aU/sjCB8fzxtP2/jipZsjOx8ILvuxXGxvifil+YIm6KnzvaO8Yetk7JzAM0pM//Q=="
//             }, trxid=211215113309477077, trxstatus=0000, reqsn=1639540552221, retcode=SUCCESS
//        }
        log.info("通联拉起支付返回字段：" +map);
        if("0000".equals(map.get("trxstatus"))){
            Map payInfoMap = JSON.parseObject(map.get("payinfo"), Map.class);
            resultInfo.put("payTimeStamp", payInfoMap.get("timeStamp"));
            resultInfo.put("paynonceStr", payInfoMap.get("nonceStr"));
            resultInfo.put("paySignType", payInfoMap.get("signType"));
            resultInfo.put("merchantsNumber", map.get("trxid")); //商户单号（商户）
            resultInfo.put("ordNo", map.get("reqsn"));
            resultInfo.put("payPackage", payInfoMap.get("package"));
            resultInfo.put("paySign", payInfoMap.get("paySign"));
            resultInfo.put("payAppId", payInfoMap.get("appId"));
            resultInfo.put("source", map.get("payinfo"));           //支付宝流水号或支付宝支付链接
            resultInfo.put("signType", payInfoMap.get("signType"));
            //resultInfo.put("bizMsg", respData.get("bizMsg"));
            //resultInfo.put("bizCode", respData.get("bizCode"));
            //resultInfo.put("sxfUuid", respData.get("sxfUuid"));
            //resultInfo.put("uuid", respData.get("uuid"));
            //resultInfo.put("orgId", result.get("orgId"));
            //resultInfo.put("reqId", result.get("reqId"));
        }else {
            resultInfo.put("code", map.get("trxstatus"));
            resultInfo.put("msg", map.get("errmsg"));
        }
        return resultInfo;
    }







    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map<String,String> handleResult(String result, TLPayParam tlPayParam) throws Exception{
        System.out.println("ret:"+result);
        Map map = SybUtil.json2Obj(result, Map.class);
        if(map == null){
            throw new Exception("返回数据错误");
        }
        if("SUCCESS".equals(map.get("retcode"))){
            TreeMap tmap = new TreeMap();
            tmap.putAll(map);
            String appkey = "";
            if(SybConstants.SIGN_TYPE.equals("RSA"))
                appkey = SybConstants.SYB_RSATLPUBKEY;
            else if(SybConstants.SIGN_TYPE.equals("SM2"))
                appkey = SybConstants.SYB_SM2TLPUBKEY;
            else
                appkey = SybConstants.SYB_MD5_APPKEY;
            if(SybUtil.validSign(tmap, appkey, SybConstants.SIGN_TYPE)){
                System.out.println("签名成功");
                return map;
            }else{
                throw new Exception("验证签名失败");
            }

//            TreeMap tmap = new TreeMap();
//            tmap.putAll(map);
//            String appkey = "";
//            if(tlPayParam.getSIGN_TYPE().equals("RSA"))
//                appkey = tlPayParam.getSYB_RSACUSPRIKEY();
//            else if(tlPayParam.getSIGN_TYPE().equals("SM2"))
//                appkey = tlPayParam.getSYB_SM2PPRIVATEKEY();
//            else
//                appkey = tlPayParam.getSYB_MD5_APPKEY();
//            if(SybUtil.validSign(tmap, appkey, tlPayParam.getSIGN_TYPE())){
//                System.out.println("签名成功");
//                return map;
//            }else{
//                throw new Exception("验证签名失败");
//            }

        }else{
            throw new Exception(map.get("retmsg").toString());
        }
    }
}
